package com.shunhao.mvp

import com.blankj.utilcode.util.GsonUtils
import com.shunhao.utils.LogUtil
import io.reactivex.disposables.Disposable
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.RequestBody
import okhttp3.RequestBody.Companion.toRequestBody
import java.lang.ref.WeakReference
import java.util.*

/**
 * ClassName:BasePresenter
 * Package:com.shunhao.mvp
 * Description:
 * Com:shunHao.com
 * @date:2020/10/13 16:17
 * @author:827746955@qq.com
 */
open class BasePresenter<V> {

    companion object {
        private val TAG: String = BasePresenter::class.java.simpleName
    }

    private var mViewRef: WeakReference<V>? = null
    private var rxLife: com.shunhao.network.rxjava.RxLife? = null

    fun attachView(view: V) {
        mViewRef = WeakReference<V>(view)
        rxLife = com.shunhao.network.rxjava.RxLife.create()
    }

    fun getView(): V? {
        return mViewRef?.get()
    }

    fun addToRxLife(disposable: Disposable) {
        rxLife?.add(disposable)
    }

    fun isViewAttached(): Boolean {
        return mViewRef != null && mViewRef?.get() != null
    }

    fun detachView() {
        LogUtil.d(TAG, "[BasePresenter detachView]")
        mViewRef?.clear()
        mViewRef = null
        rxLife?.destroy()
        rxLife = null
    }

    fun getRequestBody2Json(commitHashMap: HashMap<String, Any>): RequestBody {
        val json = GsonUtils.toJson(commitHashMap)
        return json.toRequestBody("application/json".toMediaType())
    }

    fun parseRequestBody(value: String): RequestBody {
        return value.toRequestBody("text/plain".toMediaType())
    }

}